<template>
  <div class="app-container">
    <!-- 搜索和操作区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.native.prevent>
        <el-form-item label="部门名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入部门名称"
            clearable
            size="small"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button size="small" icon="el-icon-search" type="primary" @click="handleSearch">搜索</el-button>
          <el-button size="small" @click="resetSearch" icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="content-container">
      <div class="content-header">
        <span class="title">部门列表</span>
        <div class="action-buttons-container">
          <el-button type="primary" size="small" @click="dialogFormVisible = true; dept={}" icon="el-icon-plus">新增部门</el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        :header-cell-style="{background:'#fafafa',color:'#606266',fontWeight: 'bold'}"
        stripe
        empty-text="暂无部门数据"
      >
        <el-table-column type="index" width="100" label="序号" align="center" :index="calculateIndex" />
        <el-table-column prop="name" label="部门名称" align="center" />
        <el-table-column label="最后操作时间" align="center">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="420" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="selectById(scope.row.id)"
            >编辑</el-button>

            <el-button
              size="mini"
              type="danger"
              @click="deleteById(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
<!--    <div class="pagination-container">-->
<!--      <el-pagination-->
<!--        background-->
<!--        :current-page="currentPage"-->
<!--        :page-sizes="[5, 10, 20, 50]"-->
<!--        :page-size="pageSize"-->
<!--        layout="total, sizes, prev, pager, next, jumper"-->
<!--        :total="total"-->
<!--        @size-change="handleSizeChange"-->
<!--        @current-change="handleCurrentChange"-->
<!--      />-->
<!--    </div>-->

    <!-- 新建/编辑对话框 -->
    <el-dialog title="保存部门" :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="dept" ref="deptForm" :rules="deptRules">
        <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="dept.name" placeholder="请输入部门名称" autocomplete="off" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById } from '@/api/dept.js'

export default {
  data() {
    return {
      formLabelWidth: '120px',
      dialogFormVisible: false, // 控制对话框是否可见
      dept: {
        name: ''
      },
      tableData: [],
      searchForm: {
        name: ''
      },
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      deptRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 当页面加载完成后自动执行。
    this.init()
  },

  methods: {

    // 删除部门
    deleteById(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(id).then((result) => {
          if (result.data.code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
          } else {
            this.$message.error(result.data.msg)
          }
          // 重新查询数据
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 根据ID查询部门 -- 回显
    selectById(id) {
      this.dialogFormVisible = true
      selectById(id).then((result) => {
        this.dept = result.data.data
      })
    },

    // 保存方法
    add() {
      let method // 添加
      if (this.dept.id) {
        method = update(this.dept) // 修改
      } else {
        method = add(this.dept) // 添加
      }
      method.then((result) => {
        if (result.data.code === 1) {
          // 修改成功
          this.$message.success('恭喜你，保存成功')
          // 重新查询数据
          this.init()
        } else {
          this.$message.error(result.data.msg)
        }
      })
      // 关闭新建窗口
      this.dialogFormVisible = false

      // 清空模型数据
      this.dept = {}
    },

    // 初始化 - 查询全部
    init() {
      this.loading = true
      const params = {
        name: this.searchForm.name, // 搜索的部门名称
        page: this.currentPage, // 当前页码，对应后端 page 参数
        size: this.pageSize // 每页大小，对应后端 size 参数
      }
      page(params).then((result) => {
        console.log('后端返回结果:', result.data) // 更详细地打印后端实际返回的数据
        if (result.data.code === 1) {
          if (Array.isArray(result.data.data)) {
            // 如果后端直接返回数组（例如：在 /depts 接口未完全支持分页时）
            this.tableData = result.data.data
            this.total = result.data.data.length // 总数取数组长度
          } else if (result.data.data && result.data.data.rows !== undefined && result.data.data.total !== undefined) {
            // 如果后端返回的是分页对象格式 (code=1, data={rows: [], total: 0})，这是预期的
            this.tableData = result.data.data.rows
            this.total = result.data.data.total
          } else {
            // 兜底情况，数据结构不符合预期
            console.warn('后端返回的data结构不符合预期，可能缺少 rows 或 total 字段:', result.data.data)
            this.tableData = []
            this.total = 0
          }
        } else {
          this.$message.error(result.data.msg || '获取部门数据失败')
          this.tableData = []
          this.total = 0
        }
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.$message.error('获取部门数据失败，请检查网络或后端服务')
        console.error('Error fetching department data:', error)
      })
    },

    handleSearch() {
      this.currentPage = 1
      this.init()
    },

    resetSearch() {
      this.searchForm.name = ''
      this.currentPage = 1
      this.init()
    },

    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.currentPage = 1
      this.init()
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.init()
    },

    formatDateTime(dateTime) {
      if (dateTime) {
        return dateTime.replace('T', ' ')
      }
      return ''
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-bottom: 0;
  vertical-align: middle;
}

.search-form .el-form-item:not(:last-child) {
  margin-right: 20px;
}

.content-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 20px;
  margin-bottom: 20px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.content-header .title {
  font-size: 16px;
  font-weight: bold;
}

.pagination-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 20px;
  text-align: right;
}

.el-table {
  border-top: 1px solid #e4e7ed;
}
.el-table th {
  background-color: #fafafa !important;
  color: #606266 !important;
  font-weight: 600;
  font-size: 13px;
  border-bottom: 1px solid #e4e7ed;
}
.el-table td {
  border-bottom: 1px solid #f0f0f0;
}
.el-table .el-table__row:hover {
  background-color: #f8f9fa;
}

@media (max-width: 900px) {
  .search-container {
    padding: 15px;
  }
  .content-container {
    padding: 15px;
  }
  .content-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .action-buttons-container {
    margin-top: 12px;
  }
  .search-form {
    display: flex;
    flex-direction: column;
    width: 100%;
  }
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }
  .search-form .el-form-item:not(:last-child) {
    margin-right: 0;
  }
}
</style>

<style>
/* 暗色主题适配：仅在 body.dark-theme 下生效 */
body.dark-theme .app-container,
body.dark-theme .search-container,
body.dark-theme .content-container,
body.dark-theme .pagination-container {
  background-color: #1f1f1f !important;
  color: #fff !important;
}
body.dark-theme .el-table,
body.dark-theme .el-table th,
body.dark-theme .el-table td {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-table th {
  background-color: #232323 !important;
  color: #fff !important;
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .el-table td {
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .el-table .el-table__row:hover {
  background-color: #2b2b2b !important;
}
body.dark-theme .el-input__inner,
body.dark-theme .el-select .el-input__inner {
  background-color: #232323 !important;
  color: #fff !important;
  border-color: #444 !important;
}
body.dark-theme .el-button--primary {
  background-color: #409eff !important;
  border-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-button--danger {
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
  color: #fff !important;
}
body.dark-theme .el-button--success {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
  color: #fff !important;
}
body.dark-theme .el-button--info {
  background-color: #909399 !important;
  border-color: #909399 !important;
  color: #fff !important;
}
body.dark-theme .el-button--warning {
  background-color: #e6a23c !important;
  border-color: #e6a23c !important;
  color: #fff !important;
}
body.dark-theme .el-pagination,
body.dark-theme .el-pagination__total,
body.dark-theme .el-pagination__jump,
body.dark-theme .el-pagination__editor,
body.dark-theme .el-pagination__sizes,
body.dark-theme .el-pagination__sizes .el-input__inner {
  background-color: #1f1f1f !important;
  color: #fff !important;
  border-color: #444 !important;
}
body.dark-theme .el-dialog {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-dialog__header {
  background-color: #232323 !important;
  color: #fff !important;
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .el-dialog__title {
  color: #fff !important;
}
body.dark-theme .el-dialog__body {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-form-item__label {
  color: #fff !important;
}
body.dark-theme .el-select-dropdown {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-select-dropdown__item.selected {
  background-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-select-dropdown__item:hover {
  background-color: #2b2b2b !important;
  color: #fff !important;
}
</style>
